<template>
  <div class="login-container">
    <!-- 流动背景容器 -->
    <div class="animated-background">
      <div class="bg-bubbles">
        <li v-for="i in 20" :key="i" :style="bubbleStyle(i)"></li>
      </div>
      <div class="floating-elements">
        <div class="floating-book" :style="floatingStyle(1)">📚</div>
        <div class="floating-gear" :style="floatingStyle(2)">⚙️</div>
        <div class="floating-graph" :style="floatingStyle(3)">📊</div>
        <div class="floating-code" :style="floatingStyle(4)">💻</div>
        <div class="floating-light" :style="floatingStyle(5)">💡</div>
      </div>
      <div class="particles-container">
        <div
          v-for="i in 50"
          :key="'particle-' + i"
          class="particle"
          :style="particleStyle(i)"
        ></div>
      </div>
    </div>

    <el-card class="login-box">
      <template #header>
        <div class="login-header">
          <h2 class="login-title">在线教育平台</h2>
          <p class="login-subtitle">知识改变命运 · 学习成就未来</p>
        </div>
      </template>
      
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <!-- 用户名输入 -->
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            size="large"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 密码输入 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <!-- 角色选择 -->
        <el-form-item prop="role">
          <el-select
            v-model="loginForm.role"
            placeholder="请选择角色"
            style="width: 100%"
            size="large"
          >
            <el-option label="学生" value="student"></el-option>
            <el-option label="教师" value="teacher"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>

        <!-- 记住我 -->
        <el-form-item prop="remember">
          <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
        </el-form-item>

        <!-- 拼图验证 -->
        <el-form-item prop="verified">
          <div class="verify-container">
            <!-- 仅当未验证时显示按钮 -->
            <el-button
              v-if="!loginForm.verified"
              type="primary"
              plain
              @click="showPuzzle"
              size="large"
              style="width: 100%"
            >
              点击进行安全验证
            </el-button>

            <!-- 验证通过时显示成功提示 -->
            <div v-else class="verify-success">
              <el-icon color="#67C23A"><CircleCheck /></el-icon>
              <span>验证通过</span>
            </div>

            <PuzzleVcode
              v-model:show="isShowPuzzle"
              @success="handleVerifySuccess"
            />
          </div>
        </el-form-item>

        <!-- 登录按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="login-btn"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <el-link type="primary" @click="gotoRegister">注册账号</el-link>
        <el-link type="info" @click="gotoForget">忘记密码</el-link>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElCard } from "element-plus";
import { CircleCheck } from "@element-plus/icons-vue";
import PuzzleVcode from "vue3-puzzle-vcode";
import http from "../util/request";
import { User, Lock } from "@element-plus/icons-vue";
const icons = { User, Lock };

const router = useRouter();

// 登录表单数据
const loginForm = reactive({
  username: "",
  password: "",
  role: "",
  remember: false,
  verified: false,
});

// 表单验证规则
const loginRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  role: [{ required: true, message: "请选择角色", trigger: "change" }],
  verified: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请完成安全验证"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
});

const isShowPuzzle = ref(false);
const loginFormRef = ref(null);
const loading = ref(false);

// 动画状态
const animationState = ref(0);

// 气泡样式
const bubbleStyle = (index) => {
  const size = Math.random() * 80 + 20;
  const duration = Math.random() * 20 + 10;
  const delay = Math.random() * 5;
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${Math.random() * 100}%`,
    animationDuration: `${duration}s`,
    animationDelay: `${delay}s`,
    opacity: Math.random() * 0.6 + 0.2,
  };
};

// 浮动元素样式
const floatingStyle = (index) => {
  const duration = 15 + index * 2;
  const delay = index * 2;
  return {
    animationDuration: `${duration}s`,
    animationDelay: `${delay}s`,
    fontSize: `${24 + index * 4}px`,
    left: `${10 + index * 15}%`,
  };
};

// 粒子样式
const particleStyle = (index) => {
  const size = Math.random() * 4 + 1;
  const duration = Math.random() * 10 + 5;
  const delay = Math.random() * 5;
  return {
    width: `${size}px`,
    height: `${size}px`,
    left: `${Math.random() * 100}%`,
    top: `${Math.random() * 100}%`,
    animationDuration: `${duration}s`,
    animationDelay: `${delay}s`,
    opacity: Math.random() * 0.8 + 0.2,
  };
};

// 显示拼图验证弹窗
const showPuzzle = () => {
  isShowPuzzle.value = true;
};

// 验证成功回调
const handleVerifySuccess = () => {
  loginForm.verified = true;
  isShowPuzzle.value = false;
  ElMessage.success("验证通过");
};

// 登录处理
const handleLogin = async () => {
  try {
    // 验证表单
    await loginFormRef.value.validate();

    loading.value = true;

    const res = await http.post("/api/login", {
      username: loginForm.username,
      password: loginForm.password,
      role: loginForm.role,
      verifyToken: loginForm.verified ? "verified" : "",
    });

    if (res.data?.code === 200) {
      // 存储token和用户信息
      localStorage.setItem("token", res.data.data.token);
      localStorage.setItem(
        "userinfo",
        JSON.stringify({
          username: loginForm.username,
          password: loginForm.remember ? loginForm.password : "",
          role: loginForm.role,
        })
      );

      ElMessage.success("登录成功");
      router.push("/index");
    } else {
      ElMessage.error(res.data?.message || "登录失败");
      loginForm.verified = false;
    }
  } catch (error) {
    console.error("登录错误:", error);
    ElMessage.error(error.response?.data?.message || "登录失败");
    loginForm.verified = false;
  } finally {
    loading.value = false;
  }
};

// 初始化记住我数据
const initRememberData = () => {
  const userinfo = JSON.parse(localStorage.getItem("userinfo"));
  if (userinfo) {
    loginForm.username = userinfo.username;
    loginForm.password = userinfo.password || "";
    loginForm.role = userinfo.role || "";
    loginForm.remember = !!userinfo.password;
  }
};

// 跳转注册页面
const gotoRegister = () => {
  router.push("/register");
};

// 跳转忘记密码页面
const gotoForget = () => {
  router.push("/forget-password");
};

// 动画循环
let animationInterval;
onMounted(() => {
  initRememberData();
  animationInterval = setInterval(() => {
    animationState.value = (animationState.value + 1) % 100;
  }, 50);
});

onUnmounted(() => {
  clearInterval(animationInterval);
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  position: relative;
  padding: 20px;
}

.animated-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

/* 气泡动画 */
.bg-bubbles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.bg-bubbles li {
  position: absolute;
  list-style: none;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 50%;
  bottom: -100px;
  animation: square 25s infinite;
  transition-timing-function: linear;
}

@keyframes square {
  0% {
    transform: translateY(0) rotate(0deg);
    opacity: 1;
  }
  100% {
    transform: translateY(-1000px) rotate(720deg);
    opacity: 0;
  }
}

/* 浮动元素 */
.floating-elements {
  position: absolute;
  width: 100%;
  height: 100%;
}

.floating-elements div {
  position: absolute;
  animation: float 20s infinite ease-in-out;
  opacity: 0.6;
  font-size: 24px;
}

.floating-book {
  top: 20%;
  animation-delay: 0s;
}
.floating-gear {
  top: 40%;
  animation-delay: 4s;
}
.floating-graph {
  top: 60%;
  animation-delay: 8s;
}
.floating-code {
  top: 30%;
  animation-delay: 12s;
}
.floating-light {
  top: 50%;
  animation-delay: 16s;
}

@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  25% {
    transform: translateY(-20px) rotate(5deg);
  }
  50% {
    transform: translateY(0px) rotate(0deg);
  }
  75% {
    transform: translateY(20px) rotate(-5deg);
  }
}

/* 粒子效果 */
.particles-container {
  position: absolute;
  width: 100%;
  height: 100%;
}

.particle {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  animation: particle-float 15s infinite linear;
}

@keyframes particle-float {
  0% {
    transform: translateY(100vh) rotate(0deg);
    opacity: 0;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    transform: translateY(-100px) rotate(360deg);
    opacity: 0;
  }
}

/* 登录框样式增强 */
.login-box {
  width: 420px;
  border: none;
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1), 0 0 0 1px rgba(255, 255, 255, 0.1),
    0 0 50px rgba(103, 126, 234, 0.3);
  position: relative;
  z-index: 2;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.login-box :deep(.el-card__header) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 30px 30px 10px;
}

.login-header {
  text-align: center;
}

.login-title {
  margin-bottom: 10px;
  color: #667eea;
  font-size: 32px;
  font-weight: 700;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #667eea, #764ba2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.login-subtitle {
  margin-bottom: 10px;
  color: #666;
  font-size: 16px;
  font-weight: 500;
}

.login-form {
  margin-top: 20px;
  padding: 0 10px;
}

.login-btn {
  width: 100%;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border: none;
  font-size: 16px;
  height: 48px;
  border-radius: 12px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(103, 126, 234, 0.3);
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(103, 126, 234, 0.4);
}

.login-btn:active {
  transform: translateY(0);
}

/* 验证成功样式增强 */
.verify-success {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 12px;
  background: rgba(103, 194, 58, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(103, 194, 58, 0.2);
  font-weight: 500;
  color: #67c23a;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}

.el-link {
  font-size: 14px;
  transition: all 0.3s ease;
}

.el-link:hover {
  transform: translateY(-1px);
}

/* 表单输入框样式增强 */
:deep(.el-input__inner) {
  border-radius: 12px !important;
  border: 2px solid #e6e8f0 !important;
  transition: all 0.3s ease !important;
}

:deep(.el-input__inner:focus) {
  border-color: #667eea !important;
  box-shadow: 0 0 0 2px rgba(103, 126, 234, 0.2) !important;
}

:deep(.el-select .el-input__inner) {
  border-radius: 12px !important;
}

:deep(.el-checkbox__label) {
  color: #666 !important;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-box {
    width: 100%;
    margin: 20px;
  }

  .login-title {
    font-size: 28px;
  }

  .login-subtitle {
    font-size: 14px;
  }
}

/* 添加光晕效果 */
.login-box::before {
  content: "";
  position: absolute;
  top: -2px;
  left: -2px;
  right: -2px;
  bottom: -2px;
  background: linear-gradient(45deg, #667eea, #764ba2, #667eea);
  z-index: -1;
  border-radius: 22px;
  animation: border-glow 3s ease-in-out infinite alternate;
}

@keyframes border-glow {
  0% {
    opacity: 0.5;
    filter: blur(10px);
  }
  100% {
    opacity: 0.8;
    filter: blur(20px);
  }
}

/* 验证容器样式 */
.verify-container {
  width: 100%;
  margin: 10px 0;
}

/* 拼图验证弹窗样式调整 */
:deep(.vcode-modal) {
  border-radius: 16px !important;
}

:deep(.vcode-content) {
  background: linear-gradient(135deg, #667eea, #764ba2) !important;
}

:deep(.vcode-slider) {
  border-radius: 12px !important;
}
</style>